package com.github.xzb617.client.config.serv;

import com.github.xzb617.client.base.props.ClientProperties;
import com.github.xzb617.client.base.lb.ServerLoadBalanceFactory;
import com.github.xzb617.client.base.props.BaseProperties;
import com.github.xzb617.client.config.props.ClientConfigProperties;
import com.github.xzb617.rpc.LoadBalanceCaller;
import com.github.xzb617.rpc.loadbalancer.factory.LbBeanCreatedException;
import org.springframework.beans.factory.BeanCreationException;

public class ConfigServiceFactory {

    private static ConfigService configService;

    public static ConfigService getInstance(ClientProperties clientProperties, BaseProperties baseProperties, ClientConfigProperties configProperties) {
        if (configService == null) {
            synchronized (ConfigServiceFactory.class) {
                if (configService == null) {
                    LoadBalanceCaller loadBalanceCaller = null;
                    try {
                        loadBalanceCaller = ServerLoadBalanceFactory.createLoadBalanceRpcBroker(clientProperties);
                    } catch (LbBeanCreatedException e) {
                        throw new BeanCreationException(e.getMessage());
                    }
                    configService = new ConfigService(clientProperties, baseProperties, configProperties, loadBalanceCaller);
                }
            }
        }
        return configService;
    }

//    public static LoadBalanceCaller createLoadBalanceRpcBroker(ClientProperties clientProperties) throws LbBeanCreatedException {
//        List<Server> servers = generateServers(clientProperties);
//        RequestCaller rpcSender = createRpcCaller(clientProperties);
//        LoadBalancer loadBalancer = createLoadBalancer(clientProperties);
//        return new LoadBalanceCaller(servers, rpcSender, loadBalancer);
//    }
//
//    private static RequestCaller createRpcCaller(ClientProperties clientProperties) {
//        // 初始化 RpcSender
//        RpcConfig rpcConfig = new RpcConfig();
//        rpcConfig.setEncode("UTF-8");
//        rpcConfig.setTimeout(70000);
//        RequestCaller requestCaller = new HttpClientRequestCaller(rpcConfig);
//        return requestCaller;
//    }
//
//    private static LoadBalancer createLoadBalancer(ClientProperties clientProperties) throws LbBeanCreatedException {
//        return LbBeanFactory.getInstance(clientProperties.getLoadBalanceStrategy());
//    }
//
//    private static List<Server> generateServers(ClientProperties clientProperties) {
//        String serverAddr = clientProperties.getServerAddrs();
//        return ServerUtil.parseServers(serverAddr);
//    }

}
